<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\helpers\Url;

use app\utils\Functions as F;

class AuthController extends BaseController
{
    public $service = null;
    public $brandShow = false;

    public function beforeAction($action) {
        if (parent::beforeAction($action)) {
            if (!$this->isHeartClicking()) {
                $this->S(null);
                return $this->redirect(Url::to(['/site/index', 'retargetUrl' => Url::current()]));
            }
            $this->touchSession();
            return $this->isLogined();
        }
        return true;
    }   

    public function init() {
        parent::init();
        $controller = $this->id;
        $service = ucfirst($this->id).'Service';  
        $names = explode('-', $service);
        $names = array_map('ucfirst', $names);
        $service = implode($names);
        if (file_exists('../services/'.$service.'.php')) {
            $service = 'app\services\\'.$service;
            $this->service = new $service();
            $this->service->init();
        }
    }

    public function isLogined() {
        if(!$this->S('user_id')) {
            return false;
        }
        return true;
    }

    public function isAllowedSeeShows()
    {
        $userType = $this->s('user_type');
        if (in_array($userType, [1,2])) return 'true';
        return '';
    }

    /**
     * session 心跳监测
     */
    public function actionHeartBeat() {
        if (!$this->isHeartClicking()) {
            $this->S(null);
            $this->NG('session timeout!');
        }        
    }

    public function isHeartClicking() {
        $lifeSpan = \Yii::$app->params['session']['VAM_SESSION_LIFE_SPAN'];
        $lastRequestTime = $this->S('LastRequestTime');
        $intval = time() - $lastRequestTime;
        //$this->tagSession($lastRequestTime, $lifeSpan);
        return $lifeSpan > $intval;
    }

    // print session 
    public function tagSession($lastRequestTime, $lifeSpan) {
        echo 'LRT: ['.date('Y-m-d H:i:s', $lastRequestTime).'] </br>';
        echo 'Now: ['.date('Y-m-d H:i:s').'] </br>';
        $h = (int) $lifeSpan/3600;
        $m = (int) ($lifeSpan%3600)/60;
        $s = $lifeSpan%3600;
        echo " SLS: [${h}h${m}m${s}s]";
    }

    /**
     * 设置页面广告主焦点
     */
    public function actionBrandSwitch() {
        $name = $this->I('name');
        if($name == 0) {
            $adname = $this->t('common', 'All');
            $this->S('advertiser', $adname);
            $this->S('advertiser_id', 0);
            $this->OK($this->t('site', 'Current brand switched ot {brand}', ['brand'=>$adname]));
        }
        
        $name && $advertiser = $this->M('Advertiser', $name);
        if (is_array($advertiser)) {
            $adname = $advertiser['name'];
            $this->S('advertiser', $advertiser['name']);
            $this->S('advertiser_id', $advertiser['id']);
            $this->OK($this->t('site', 'Current brand switched ot {brand}', ['brand'=>$adname]));
        }
        $this->NG('Brand switching faield!');
    }

    /**
     * 设置session相关的值
     */
    public function actionSetFocusId() {
        $idName  = $this->I('focusIdName');
        $idValue = $this->I('focusIdValue');
        $this->S($idName, $idValue);
        $this->OK('session set!');
    }

    /**
     * creative preview action
     */
    public function creativePreview ($creative='') {
        $creativeId = $this->I('id');
        $table = 'Creative';
        if (!$creative) {
            $creative = $this->getOne($table, ['id' => $creativeId]);
        }
        $service = new \app\services\CreativeService();
        //$code = $service->getSspCreativeCode($creativeId);
        //$code = preg_replace('/(\{\![\w_]*\}){1,}http/i', 'http', $code);
        $code = $service->replaceCreativeCodeMacros($creative);
        $this->preview($creative, $code);
    }
    
    public function preview($creative, $data='') {
        $this->layout = 'creativePreview';
        if ($creative['type'] == 5) exit($data);
        $this->data = $data;
        $this->creative = $creative;
        return $this->show('/creative/listAppCreativePreview');
    }

    public function actionMobileCreativePreview() {
        $creativeId = $this->I('id');
        $table = 'Creative';
        $creative = $this->getOne($table, ['id' => $creativeId]);
        if (!$creative) {
            $data = $this->t('site', 'Creative not found!');
            return $this->preview($data);
        }
        if ($this->I('type') == 'mobile-app') {
            $data = $this->getInAppMobileCreative($creative);
            return $this->preview($creative, $data);
        } else if ($this->I('type') == 'mobile-web') {
            $this->creativePreview($creative);
        }
    }

    /**
     * 组合输出 json 类型的 in app 创意内容
     */
    public function getInAppMobileCreative($creative) {
        $title = $creative['title'];
        $txt = $creative['txt'];
        $imgs = $creative['file_url'];
        $imgs = explode(',', $imgs);
        $div = "<p>$title</p><p>$txt</p>";
        foreach ($imgs as $img) {
            $div .= "<img src='$img' >";
        }
        return $div;
    }
}// end of auth controller
